<?php

require_once LIBRARIES_ENTITIES_DATABASE;
require_once LIBRARIES_ENTITIES_USERS;
require_once LIBRARIES_ENTITIES_SLIDESHOW;


require_once LIBRARIES_TOOLS_UTILITY;
require_once LIBRARIES_TOOLS_XTEMPLATE;
require_once LIBRARIES_TOOLS_PAGERBACKEND;

class SlideshowController {

    public function invoke() {

        // function list
        $groupFunctions = $_SESSION['groupFunctions'];

        // directory path
        $dir = dirname(__FILE__);

        $view = '';
        if (isset($_GET['view'])) {
            $view = $_GET['view'];
        }

        $action = '';
        if (isset($_POST['hdAction'])) {
            $action = $_POST['hdAction'];
        }



        $task = '';
        if (isset($_GET['task'])) {
            $task = $_GET['task'];
        }


        $rowToView = 10;
        if (isset($_POST["limit"])) {
            $rowToView = $_POST["limit"];
        }

        // serID
        $userID = $_SESSION["session"]["sUserID"];


        switch ($action) {
            case 'orderdown':
                $ID = $_POST["hdID"];
                $result = $this->orderSlideshow($ID, 'down');
                break;
            case 'orderup':
                $ID = $_POST["hdID"];
                $result = $this->orderSlideshow($ID, 'up');
                break;
            case "publish":
                $values = $_POST["cid"];
                $result = $this->updateStatus($values, true);
                break;
            case "unpublish":
                $values = $_POST["cid"];
                $result = $this->updateStatus($values, false);
                break;
            case 'remove':
                $values = $_POST["cid"];
                $result = $this->deleteSlideshow($values);
                if ($result == OK) {
                    Utility::messageBox('Xóa thành công');
                    Utility::redirectCurrentPage();
                }
                break;
            case 'add':
            case 'addAndExit':
                $title = $_POST['txtTitle'];
                $image = $_POST['hdImage'];
                $link = $_POST['txtLink'];
                $createdDate = Utility::formatDateTime($_POST['txtCreatedDate']);
                $status = $_POST['rdoStatus'];

                $result = $this->addSlideshow($image, $title, $link, $createdDate, $status, $userID);
                if ($result == OK) {
                    if ($action == 'add') {
                        Utility::messageBox('Thêm thành công');
                        Utility::redirectCurrentPage();
                    } else {
                        Utility::redirect(".?com=com_slideshow&task=view");
                    }
                }

                break;
            case 'edit':
            case 'editAndExit':
                $ID = $_POST['hdID'];
                $title = $_POST['txtTitle'];
                $image = $_POST['hdImage'];
                $link = $_POST['txtLink'];
                $createdDate = Utility::formatDateTime($_POST['txtCreatedDate']);
                $status = $_POST['rdoStatus'];

                $result = $this->updateSlideshow($ID, $image, $title, $link, $createdDate, $status, $userID);

                if ($result == OK) {
                    if ($action == 'edit') {
                        Utility::messageBox('Sửa thành công');
                        Utility::redirectCurrentPage();
                    } else {
                        Utility::redirect(".?com=com_slideshow&task=view");
                    }
                }
                break;
        }






        if ($task == 'view') {
            // check view permission
            if (Utility::checkPermission('view', $groupFunctions, SLIDESHOW_MANAGEMENT)) {

                $viewFile = $dir . '/views/slideshow_list.html';

                $xtemplate = new XTemplate($viewFile);

                // CHECK PERMISSION
                // check add button
                if (Utility::checkPermission('add', $groupFunctions, SLIDESHOW_MANAGEMENT)) {
                    $xtemplate->parse('main.add_button');
                }
                // check delete button
                if (Utility::checkPermission('delete', $groupFunctions, SLIDESHOW_MANAGEMENT)) {
                    $xtemplate->parse('main.delete_button');
                }
                // check enable button
                if (Utility::checkPermission('enable', $groupFunctions, SLIDESHOW_MANAGEMENT)) {
                    $xtemplate->parse('main.enable_button');
                }
                // check disable button
                if (Utility::checkPermission('disable', $groupFunctions, SLIDESHOW_MANAGEMENT)) {
                    $xtemplate->parse('main.disable_button');
                }


                $indexCheckBox = 1;

                $rurrentPage = 1;
                if (isset($_POST["page"])) {
                    $rurrentPage = $_POST["page"];
                }


                // chỉ mục (số thứ tự của bài viết) bài viết
                $index = 1;

                $slideshows = $this->getSlideshowList();

                $pager = PagerBackEnd::getPagerData(count($slideshows), $rowToView, $rurrentPage);


                if ($slideshows != null) {

                    $indexCheckBox = 1;


                    foreach ($slideshows as $slideshow) {

                        if ($index > $pager->offset && $index <= $pager->limit) {

                            $xtemplate->assign('INDEX', $index);
                            $xtemplate->assign('INDEX_CHECKBOX', $indexCheckBox);

                            $xtemplate->assign('ID', $slideshow->getID());
                            $xtemplate->assign('IMAGE', $slideshow->getImage());
                            $xtemplate->assign('TITLE', $slideshow->getTitle());
                            $xtemplate->assign('CREATED_USER', $slideshow->getCreatedUser()->getFullname());
                            $xtemplate->assign('MODIFIED_USER', $slideshow->getModifiedUser()->getFullname());
                            $xtemplate->assign('CREATED_DATE', Utility::formatDateTimeToView($slideshow->getCreatedDate()));
                            $xtemplate->assign('MODIFIED_DATE', Utility::formatDateTimeToView($slideshow->getModifiedDate()));
                            $xtemplate->assign('LINK', $slideshow->getLink());


                            // check update permission                            
                            if (Utility::checkPermission('update', $groupFunctions, SLIDESHOW_MANAGEMENT)) {
                                $xtemplate->parse('main.slideshow_list.update_button');
                            } else {
                                $xtemplate->parse('main.slideshow_list.update_button_disable');
                            }


                            // status
                            if ($slideshow->getStatus() == 1) {
                                $xtemplate->assign('STATUS_ACTION', 'unpublish');
                                $xtemplate->assign('STATUS_IMAGE', 'publish_g.png');
                            } else {
                                $xtemplate->assign('STATUS_ACTION', 'publish');
                                $xtemplate->assign('STATUS_IMAGE', 'publish_r.png');
                            }

                            // order
                            if ($index == 1) {
                                $xtemplate->parse('main.slideshow_list.down_arrow');
                            } else if ($index == count($slideshow)) {
                                $xtemplate->parse('main.slideshow_list.up_arrow');
                            } else {
                                $xtemplate->parse('main.slideshow_list.up_down_arrow');
                            }

                            $xtemplate->parse('main.slideshow_list');

                            $indexCheckBox++;
                        }
                        $index++;
                    }
                }

                $xtemplate->assign('LIMIT_LIST', Utility::getLimitList($rowToView));
                $xtemplate->assign('ROW_TO_VIEW', $rowToView);
                $xtemplate->assign('CURRENT_PAGE', $rurrentPage);
                $xtemplate->assign('AMOUNT_OF_PAGE', $pager->numPages);
                $xtemplate->assign('PAGING_HTML', $pager->paging);
                $xtemplate->parse('main');
                $xtemplate->out('main');
            } else {
                echo ERROR_PERMISSION;
            }
        } else if ($task == 'add') {

            // check add permission
            if (Utility::checkPermission('add', $groupFunctions, SLIDESHOW_MANAGEMENT)) {
                $xtemplate = new XTemplate($dir . '/views/slideshow_add.html');

                $xtemplate->assign('TODAY', date('d/m/Y'));
                $xtemplate->assign('UPLOAD_FOLDER', UPLOAD_FOLDER);
                $xtemplate->parse('main');
                $xtemplate->out('main');
            } else {
                echo ERROR_PERMISSION;
            }
        } else if ($task == 'edit') {

            // check add permission
            if (Utility::checkPermission('update', $groupFunctions, SLIDESHOW_MANAGEMENT)) {
                $ID = '';
                if (isset($_GET['ID'])) {
                    $ID = $_GET['ID'];
                }

                $slideshow = $this->getSlideshowByID($ID);

                if ($slideshow != null) {

                    $viewFile = $dir . '/views/slideshow_edit.html';
                    $xtemplate = new XTemplate($viewFile);

                    $xtemplate->assign('ID', $slideshow->getID());
                    $xtemplate->assign('TITLE', $slideshow->getTitle());
                    $xtemplate->assign('LINK', $slideshow->getLink());
                    $xtemplate->assign('IMAGE', $slideshow->getImage());
                    $xtemplate->assign('MODIFIED_DATE', Utility::formatDateTimeToView($slideshow->getModifiedDate()));

                    if ($slideshow->getStatus() == 1) {
                        $xtemplate->parse('main.status_true');
                    } else {
                        $xtemplate->parse('main.status_false');
                    }

                    $xtemplate->parse('main');
                    $xtemplate->out('main');
                } else {
                    Utility::redirect('.?com=com_slideshow&task=view');
                }
            } else {
                echo ERROR_PERMISSION;
            }
        }
    }

    private function getSlideshowList() {
        $db = new Database();
        try {
            $slideshow = new Slideshow();
            $result = $slideshow->getList($db);
            $db->submitChanges();
            return $result;
        } catch (Exception $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function getSlideshowByID($ID) {
        $db = new Database();
        try {
            $slideshow = new Slideshow();
            $slideshow->setID($ID);
            $result = $slideshow->getByID($db);
            $db->submitChanges();
            return $result;
        } catch (Exception $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function addSlideshow($image, $title, $link, $createdDate, $status, $userID) {
        $db = new Database();
        try {
            $slideshow = new Slideshow();
            $slideshow->setTitle($title);
            $slideshow->setImage($image);
            $slideshow->setLink($link);
            $slideshow->setCreatedDate($createdDate);
            $slideshow->setModifiedDate($createdDate);
            $slideshow->setOrder($slideshow->getMaxOrder($db));
            $slideshow->setStatus($status);
            $slideshow->setCreatedUserID($userID);
            $slideshow->setModifiedUserID($userID);
            $slideshow->add($db);
            $db->submitChanges();
            return OK;
        } catch (PDOException $ex) {
            echo $ex->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function deleteSlideshow($values) {
        $db = new Database();
        try {
            for ($i = 0; $i < count($values); $i++) {
                $slideshow = new Slideshow();
                $slideshow->setID($values[$i]);
                $slideshow->delete($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $ex) {
            echo $ex->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function updateSlideshow($ID, $image, $title, $link, $createdDate, $status, $userID) {
        $db = new Database();
        try {
            $slideshow = new Slideshow();
            $slideshow->setID($ID);
            $slideshow->setTitle($title);
            $slideshow->setImage($image);
            $slideshow->setLink($link);
            $slideshow->setModifiedDate($createdDate);
            $slideshow->setStatus($status);
            $slideshow->setModifiedUserID($userID);
            $slideshow->update($db);
            $db->submitChanges();
            return OK;
        } catch (PDOException $ex) {
            echo $ex->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function updateStatus($values, $status) {
        $db = new Database();
        try {
            for ($i = 0; $i < count($values); $i++) {
                $slideshow = new Slideshow();
                $slideshow->setStatus($status);
                $slideshow->setID($values[$i]);
                $slideshow->updateStatus($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $ex) {
            echo $ex->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function orderSlideshow($ID, $action) {
        $db = new Database();
        try {
            $slideshow = new Slideshow();
            $slideshow->setID($ID);
            if ($action == 'up') {
                $slideshow->orderUp($db);
            } else {
                $slideshow->orderDown($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

}

?>
